package com.mtw.bbs.bbsUser.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mtw.bbs.bbsUser.pojo.entity.UserRole;
import com.mtw.bbs.bbsUser.pojo.form.RoleForm;
import com.mtw.bbs.bbsUser.service.RoleMenuService;
import com.mtw.bbs.bbsUser.service.RoleResourceService;
import com.mtw.bbs.bbsUser.service.UserRoleService;
import com.mtw.bbs.common.core.constant.ServiceConstant;
import com.mtw.bbs.common.core.exception.BusinessException;
import com.mtw.bbs.userAdmin.pojo.vo.RoleVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.mtw.bbs.bbsUser.mapper.RoleMapper;
import com.mtw.bbs.bbsUser.pojo.entity.Role;
import com.mtw.bbs.bbsUser.service.RoleService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 角色逻辑层
 * @author mo
 * @email mo
 * @date 2023-10-18 15:44:13
 */
@Service("roleService")
@RequiredArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {


    private final UserRoleService userRoleService;
    private final RoleMenuService roleMenuService;
    private final RoleResourceService roleResourceService;



    /**
     * 新增角色
     */
    @Override
    @Transactional
    public boolean add(RoleForm form) {

        Role role = new Role();
        BeanUtils.copyProperties(form,role);
        boolean isSuccess = this.save(role);
        if (!CollectionUtils.isEmpty(form.getResources())){
            roleResourceService.saveBatch(role.getId(), form.getResources());
        }
        if (!CollectionUtils.isEmpty(form.getMenus())){
            roleMenuService.saveBatch(role.getId(), form.getMenus());
        }
        return isSuccess;
    }

    /**
     * 更新角色信息
     */
    @Override
    @Transactional
    public boolean update(RoleForm form) {

        Role role = new Role();
        BeanUtils.copyProperties(form,role);
        boolean isSuccess = this.updateById(role);

        roleResourceService.removeByRoleId(role.getId());
        if (!CollectionUtils.isEmpty(form.getResources())){
            roleResourceService.saveBatch(role.getId(), form.getResources());
        }

        roleMenuService.removeByRoleId(role.getId());
        if (!CollectionUtils.isEmpty(form.getMenus())){
            roleMenuService.saveBatch(role.getId(), form.getMenus());
        }
        return isSuccess;
    }


    /**
     * 根据id删除角色
     */
    @Override
    @Transactional
    public boolean delete(String[] ids) {
        if (ids == null || ids.length <1){
            return false;
        }
        List<String> list = Arrays.asList(ids);
        roleResourceService.removeByRoleIds(list);
        roleMenuService.removeByRoleIds(list);
        userRoleService.removeByRoleIds(list);
        return removeBatchByIds(list);
    }

    /**
     * 获取角色
     */
    @Override
    public RoleVo get(String id) {
        Role role = this.getById(id);
        if (Objects.isNull(role)) {
            throw new BusinessException("role not found with id:" + id);
        }
        RoleVo roleVo = role.toVo();
        roleVo.setResources(roleResourceService.queryByRoleId(id));
        roleVo.setMenus(roleMenuService.queryByRoleId(id));
        return roleVo;
    }




    /**
     * 根据用户id查询用户拥有的角色
     */
    @Override
    public List<RoleVo> queryByUserId(String userId) {

        Set<String> roleIds = userRoleService.queryByUserId(userId);
        if (CollectionUtils.isEmpty(roleIds)){
            return new ArrayList<>(1);
        }
        LambdaQueryWrapper<Role> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Role::getStatus, ServiceConstant.STATUS_ENABLE);
        lqw.in(Role::getId,roleIds);
        List<Role> list = list(lqw);
        if (CollectionUtils.isEmpty(list)){
            return new ArrayList<>(1);
        }
        return list.stream().map(Role::toVo).toList();
    }



    /**
     * 根据用户id集合查询用户拥有的角色
     */
    @Override
    public Map<String, List<RoleVo>> queryByUserIds(Collection<String> userIds) {

        LambdaQueryWrapper<UserRole> urqw = new LambdaQueryWrapper<>();
        urqw.in(UserRole::getUserId, userIds);
        List<UserRole> userRoleList = userRoleService.list(urqw);
        if (CollectionUtils.isEmpty(userRoleList)){
            return new HashMap<>(1);
        }

        Set<String> roleIds = userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toSet());
        LambdaQueryWrapper<Role> lqw = new LambdaQueryWrapper<>();
        lqw.select(Role::getId,Role::getRoleName);
        lqw.in(Role::getId,roleIds);
        List<Role> list = list(lqw);
        if (CollectionUtils.isEmpty(list)){
            return new HashMap<>(1);
        }

        Map<String, RoleVo> roleMap = list.stream().map(Role::toVo).collect(Collectors.toMap(RoleVo::getId, Function.identity()));
        Map<String, List<RoleVo>> result = new HashMap<>(userIds.size());
        userRoleList.forEach(x->{
            List<RoleVo> roles = result.computeIfAbsent(x.getUserId(), k -> new ArrayList<>(8) {});
            RoleVo roleVo = roleMap.get(x.getRoleId());
            if (roleVo != null && !roles.contains(roleVo)){
                roles.add(roleVo);
            }
        });


        return result;
    }


}
